# -*- coding: utf-8 -*-
__author__ = 'aaqqxx'


import wx

import numpy as np

import matplotlib

# matplotlib采用WXAgg为后台,将matplotlib嵌入wxPython中
matplotlib.use("WXAgg")

from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg as NavigationToolbar
from matplotlib.ticker import MultipleLocator, FuncFormatter

import pylab
from matplotlib import pyplot

import time
from os.path import getctime
import matplotlib.pyplot as plt
import numpy
from matplotlib.widgets import Button
from plot_figure import calc_fft,get_data_from_all_key_list_and_filename_list,get_key_from_filename,get_raise_time,get_ylabel,get_freq_amp_of_data_by_fft,get_data_from_file,get_setting_time
import sys
import os
filename=["T_P0_M1_ap_step_0.txt","T_P0_M1_av_step_0.txt","T_P0_M1_cp_step_0.txt","T_P0_M1_fe_step_0.txt",]


wildcard = "Python source (*.py)|*.py|"     \
           "Compiled Python (*.pyc)|*.pyc|" \
           "SPAM files (*.spam)|*.spam|"    \
           "Egg file (*.egg)|*.egg|"        \
           "All files (*.*)|*.*"

######################################################################################
class MPL_Panel_base(wx.Panel):
    ''' #MPL_Panel_base面板,可以继承或者创建实例'''
    def __init__(self,parent):
        wx.Panel.__init__(self,parent=parent, id=-1)

        self.Figure = matplotlib.figure.Figure(figsize=(4,3))
        self.axes = self.Figure.add_axes([0.1,0.1,0.8,0.8])
        self.axes1 = self.axes.twinx()
        self.FigureCanvas = FigureCanvas(self,-1,self.Figure)

        #继承鼠标移动显示鼠标处坐标的事件
        self.FigureCanvas.mpl_connect('motion_notify_event',self.MPLOnMouseMove)

        self.NavigationToolbar = NavigationToolbar(self.FigureCanvas)

        self.StaticText = wx.StaticText(self,-1,label='Show Help String')

        self.SubBoxSizer = wx.BoxSizer(wx.HORIZONTAL)
        self.SubBoxSizer.Add(self.NavigationToolbar,proportion =0, border = 2,flag = wx.ALL | wx.EXPAND)
        self.SubBoxSizer.Add(self.StaticText,proportion =-1, border = 2,flag = wx.BOTTOM | wx.EXPAND |wx.ALIGN_BOTTOM)


        self.TopBoxSizer = wx.BoxSizer(wx.VERTICAL)
        self.TopBoxSizer.Add(self.SubBoxSizer,proportion =-1, border = 2,flag = wx.ALL | wx.EXPAND)
        self.TopBoxSizer.Add(self.FigureCanvas,proportion =-10, border = 2,flag = wx.ALL | wx.EXPAND)

        self.SetSizer(self.TopBoxSizer)

        ###方便调用
        self.pylab=pylab
        self.pl=pylab
        self.pyplot=pyplot
        self.numpy=np
        self.np=np
        self.plt=pyplot

    def MPLOnMouseMove(self,event):
        self.StaticText.SetLabel('  x=%s,  y=%s'%(event.xdata,event.ydata))

    def UpdatePlot(self):
        '''#修改图形的任何属性后都必须使用self.UpdatePlot()更新GUI界面 '''
        self.FigureCanvas.draw()


    def plot(self,ax,*args,**kwargs):
        '''#最常用的绘图命令plot '''
        #self.axes.plot(*args,**kwargs)
        ax.plot(*args,**kwargs)
        self.UpdatePlot()


    def semilogx(self,*args,**kwargs):
        ''' #对数坐标绘图命令 '''
        self.axes.semilogx(*args,**kwargs)
        self.UpdatePlot()

    def semilogy(self,*args,**kwargs):
        ''' #对数坐标绘图命令 '''
        self.axes.semilogy(*args,**kwargs)
        self.UpdatePlot()

    def loglog(self,*args,**kwargs):
        ''' #对数坐标绘图命令 '''
        self.axes.loglog(*args,**kwargs)
        self.UpdatePlot()


    def grid(self,flag=True):
        ''' ##显示网格  '''
        if flag:
            self.axes.grid()
        else:
            self.axes.grid(False)


    def title_MPL(self,TitleString="wxMatPlotLib Example In wxPython"):
        ''' # 给图像添加一个标题   '''
        self.axes.set_title(TitleString)


    def xlabel(self,XabelString="X"):
        ''' # Add xlabel to the plotting    '''
        self.axes.set_xlabel(XabelString)


    def ylabel(self,YabelString="Y"):
        ''' # Add ylabel to the plotting '''
        self.axes.set_ylabel(YabelString)


    def xticker(self,major_ticker=1.0,minor_ticker=0.1):
        ''' # 设置X轴的刻度大小 '''
        self.axes.xaxis.set_major_locator( MultipleLocator(major_ticker) )
        self.axes.xaxis.set_minor_locator( MultipleLocator(minor_ticker) )


    def yticker(self,major_ticker=1.0,minor_ticker=0.1):
        ''' # 设置Y轴的刻度大小 '''
        self.axes.yaxis.set_major_locator( MultipleLocator(major_ticker) )
        self.axes.yaxis.set_minor_locator( MultipleLocator(minor_ticker) )


    def legend(self,*args,**kwargs):
        ''' #图例legend for the plotting  '''
        self.axes.legend(*args,**kwargs)


    def xlim(self,x_min,x_max):
        ''' # 设置x轴的显示范围  '''
        self.axes.set_xlim(x_min,x_max)


    def ylim(self,y_min,y_max):
        ''' # 设置y轴的显示范围   '''
        self.axes.set_ylim(y_min,y_max)


    def savefig(self,*args,**kwargs):
        ''' #保存图形到文件 '''
        self.Figure.savefig(*args,**kwargs)


    def cla(self):
        ''' # 再次画图前,必须调用该命令清空原来的图形  '''
        self.axes.clear()
        self.Figure.set_canvas(self.FigureCanvas)
        self.UpdatePlot()

    def ShowHelpString(self,HelpString="Show Help String"):
        ''' #可以用它来显示一些帮助信息,如鼠标位置等 '''

        self.StaticText.SetLabel(HelpString)

################################################################

class MPL_Panel(MPL_Panel_base):
    ''' #MPL_Panel重要面板,可以继承或者创建实例 '''
    def __init__(self,parent):
        MPL_Panel_base.__init__(self,parent=parent)

        #测试一下
        self.FirstPlot()


    #仅仅用于测试和初始化,意义不大
    def FirstPlot(self):
        #self.rc('lines',lw=5,c='r')
        self.cla()
        x = np.arange(-5,5,0.25)
        y = np.sin(x)
        self.yticker(0.5,0.1)
        self.xticker(1.0,0.2)
        self.xlabel('X')
        self.ylabel('Y')
        self.title_MPL("wxMatPlotLib Example In wxPython")
        self.grid()
        self.plot(self.axes,x,y,'--^g')#test!!!!


###############################################################################
#  MPL_Frame添加了MPL_Panel的1个实例
###############################################################################
class MPL_Frame(wx.Frame):
    """MPL_Frame可以继承,并可修改,或者直接使用"""
    def __init__(self,title="MPL_Frame Example In wxPython",size=(800,500)):
        wx.Frame.__init__(self,parent=None,title = title,size=size)

        self.MPL = MPL_Panel_base(self)
        self.log = ""
        #创建FlexGridSizer
        self.FlexGridSizer=wx.FlexGridSizer( rows=9, cols=1, vgap=5,hgap=5)
        self.FlexGridSizer.SetFlexibleDirection(wx.BOTH)

        self.RightPanel = wx.Panel(self,-1)

        #测试按钮1
        self.Button1 = wx.Button(self.RightPanel,-1,"TestButton",size=(100,40),pos=(10,10))
        self.Button1.Bind(wx.EVT_BUTTON,self.Button1Event)

        #测试按钮2
        self.Button2 = wx.Button(self.RightPanel,-1,"AboutButton",size=(100,40),pos=(10,10))
        self.Button2.Bind(wx.EVT_BUTTON,self.Button2Event)

        self.fftBtn = wx.Button(self.RightPanel,-1,"FFT",size=(100,40),pos=(10,10))
        self.fftBtn.Bind(wx.EVT_BUTTON,self.fftBtnEvent)

        self.fileBtn = wx.Button(self.RightPanel,-1,"OpenFile",size=(100,40),pos=(10,10))
        self.fileBtn.Bind(wx.EVT_BUTTON,self.fileBtnEvent)

        #加入Sizer中
        self.FlexGridSizer.Add(self.Button1,proportion =0, border = 5,flag = wx.ALL | wx.EXPAND)
        self.FlexGridSizer.Add(self.Button2,proportion =0, border = 5,flag = wx.ALL | wx.EXPAND)
        self.FlexGridSizer.Add(self.fftBtn,proportion =0,border =5,flag=wx.ALL | wx.EXPAND)
        self.FlexGridSizer.Add(self.fileBtn,proportion=0,border=5, flag=wx.ALL | wx.EXPAND)

        self.RightPanel.SetSizer(self.FlexGridSizer)

        self.BoxSizer=wx.BoxSizer(wx.HORIZONTAL)
        self.BoxSizer.Add(self.MPL,proportion =-10, border = 2,flag = wx.ALL | wx.EXPAND)
        self.BoxSizer.Add(self.RightPanel,proportion =0, border = 2,flag = wx.ALL | wx.EXPAND)

        self.SetSizer(self.BoxSizer)


        #状态栏
        self.StatusBar()

        #MPL_Frame界面居中显示
        self.Centre(wx.BOTH)

    #按钮事件,用于测试
    def Button1Event(self,event):
        #self.MPL.cla()#必须清理图形,才能显示下一幅图
        ax1=self.MPL.axes
        ax2=self.MPL.axes1
        ax1.clear()
        ax2.clear()
        ax2.yaxis.tick_right()
        ax2.yaxis.set_label_position('right')
        ax1.yaxis.tick_left()
        ax1.yaxis.set_label_position('left')
        #ax1.set_xlim(0,6)
        ax1.plot([1,2,3,4])
        ax1.set_xlim(0,6)#需要放在plot之后才能生效！！！～～
        self.MPL.UpdatePlot()
#        x=np.arange(-10,10,0.25)
#        y=np.cos(x)
#        self.MPL.plot(self.MPL.axes,x,y,'--*g')#test!!!!!
#        self.MPL.xticker(2.0,0.5)
#        self.MPL.yticker(0.5,0.1)
#        self.MPL.title_MPL("MPL1")
#        self.MPL.ShowHelpString("You Can Show MPL Helpful String Here !")
#        self.MPL.grid()
#        plt.draw()
#        self.MPL.UpdatePlot()#必须刷新才能显示

    def Button2Event(self,event):
        self.AboutDialog()

    def fftBtnEvent(self,event,mode="step"):
        filename_list=["T_P0_M1_ap_step_0.txt","T_P0_M1_av_step_0.txt","T_P0_M1_cp_step_0.txt","T_P0_M1_fe_step_0.txt",]
        data_all={}.fromkeys(('ap','cp','av','cv','ca','aa','fe','None'),0)

        ax1=self.MPL.axes
        ax2=self.MPL.axes1
        ax1.clear()
        ax2.clear()
        data_gather_period=200
        x1_unit='ms'
        #~~~~~~~~将本次运动采集的所有数据都读取进来~~~~~~~~~
        for key in data_all:
            for each_file in filename_list:
                if key in each_file:
                    data_all[key]=get_data_from_file(each_file)
                    break
            #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#

        #~~~~~~~~根据需要绘制的文件名，得到相应的key，用于字典存放数据

        key_list_for_plot=[]
        for each in filename_list:
            key_list_for_plot.append(get_key_from_filename(each))

        line_data=get_data_from_all_key_list_and_filename_list(key_list_for_plot,filename_list,data_all)
        freq1,spectrum_f1,freq2,spectrum_f2,freq3,spectrum_f3,freq4,spectrum_f4=calc_fft(line_data[0],line_data[1],line_data[2],line_data[3],dt=float(data_gather_period),dt_unit='us')

        ax1.clear()
        ax2.clear()

        ax1.set_yscale('log')
        ax2.set_yscale('log')
        ax1.xaxis.grid(True, which='major')
        ax1.xaxis.grid(True, which='minor')

        line1 = ax1.plot(freq1[:len(spectrum_f1)/2],spectrum_f1[:len(spectrum_f1)/2],color = 'b')
        line2 = ax1.plot(freq2[:len(spectrum_f2)/2],spectrum_f2[:len(spectrum_f2)/2],color = 'g')
        line3 = ax2.plot(freq3[:len(spectrum_f3)/2],spectrum_f3[:len(spectrum_f3)/2],color = 'r',)
        line4 = ax2.plot(freq4[:len(spectrum_f4)/2],spectrum_f4[:len(spectrum_f4)/2],color = 'brown')

        #ax1.set_title(motor_name+' motion executed at '+executed_time)
        #ax1.set_ylabel(y2_ylabel,color='g')
        ax1.set_xlabel('freq(Hz)')

        #ax2.set_ylabel(y3_ylabel,color='r')
        ax2.yaxis.tick_right()
        ax2.yaxis.set_label_position('right')
        for tl in ax2.get_yticklabels():
            tl.set_color('r')
        ax1.grid(True)
        #ax1.set_ylim(ymin=-10)

        ax1.legend((line1,line2,line3,line4),("y1_ylabel","y2_ylabel","y3_ylabel","y4_ylabel"),loc='best')#get_freq_amp_of_data_by_fft

        if (mode=='step'):
            cmd_position = max(data_all['cp'])
            raise_time = str(get_raise_time(data_all['ap'],cmd_position))
            setting_time = str(get_setting_time(data_all['ap'][:len(data_all['ap'])/4],cmd_position))
            str_annotate = 'raise time=' + raise_time + x1_unit+"     the setting time="+ setting_time + x1_unit
            ax1.annotate(str_annotate, xy=(0.2, 0),  xycoords='figure fraction',
                xytext=(20, 20), textcoords='offset points',
                ha="left", va="bottom",
            )

        #plt.axis([0,1000,0,max(spectrum_f1)])
        plt.draw()
        self.MPL.UpdatePlot()


    #打开文件,用于测试
    def DoOpenFile(self):
        wildcard = r"Data files (*.dat)|*.dat|Text files (*.txt)|*.txt|ALL Files (*.*)|*.*"
        open_dlg = wx.FileDialog(self,message='Choose a file',wildcard = wildcard, style=wx.OPEN|wx.CHANGE_DIR)
        if open_dlg.ShowModal() == wx.ID_OK:
            path=open_dlg.GetPath()
            try:
                file = open(path, 'r')
                text = file.read()
                file.close()
            except IOError, error:
                dlg = wx.MessageDialog(self, 'Error opening file\n' + str(error))
                dlg.ShowModal()

        open_dlg.Destroy()

    def fileBtnEvent(self,evt):

#        self.log.WriteText("CWD: %s\n" % os.getcwd())

        # Create the dialog. In this case the current directory is forced as the starting
        # directory for the dialog, and no default file name is forced. This can easilly
        # be changed in your program. This is an 'open' dialog, and allows multitple
        # file selections as well.
        #
        # Finally, if the directory is changed in the process of getting files, this
        # dialog is set up to change the current working directory to the path chosen.
        dlg = wx.FileDialog(
            self, message="Choose a file",
            defaultDir=os.getcwd(),
            defaultFile="",
            wildcard=wildcard,
            style=wx.OPEN | wx.MULTIPLE | wx.CHANGE_DIR
            )

        # Show the dialog and retrieve the user response. If it is the OK response,
        # process the data.
        if dlg.ShowModal() == wx.ID_OK:
            # This returns a Python list of files that were selected.
            paths = dlg.GetPaths()

 #           self.log.WriteText('You selected %d files:' % len(paths))

            for path in paths:
                print path
              #  self.log.WriteText('           %s\n' % path)

        # Compare this with the debug above; did we change working dirs?
       # self.log.WriteText("CWD: %s\n" % os.getcwd())

        # Destroy the dialog. Don't do this until you are done with it!
        # BAD things can happen otherwise!
        dlg.Destroy()

    #自动创建状态栏
    def StatusBar(self):
        self.statusbar = self.CreateStatusBar()
        self.statusbar.SetFieldsCount(3)
        self.statusbar.SetStatusWidths([-2, -2, -1])


    #About对话框
    def AboutDialog(self):
        dlg = wx.MessageDialog(self, '\twxMatPlotLib\t\nMPL_Panel_base,MPL_Panel,MPL_Frame and MPL2_Frame \n Created by Wu Xuping\n Version 1.0.0 \n 2012-02-01',
            'About MPL_Frame and MPL_Panel', wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()

###############################################################################
###  MPL2_Frame添加了MPL_Panel的两个实例
###############################################################################
class MPL2_Frame(wx.Frame):
    """MPL2_Frame可以继承,并可修改,或者直接使用"""
    def __init__(self,title="MPL2_Frame Example In wxPython",size=(850,500)):
        wx.Frame.__init__(self,parent=None,title = title,size=size)

        self.BoxSizer=wx.BoxSizer(wx.HORIZONTAL)

        self.MPL1 = MPL_Panel_base(self)
        self.BoxSizer.Add(self.MPL1,proportion =-1, border = 2,flag = wx.ALL | wx.EXPAND)

        self.MPL2 = MPL_Panel_base(self)
        self.BoxSizer.Add(self.MPL2,proportion =-1, border = 2,flag = wx.ALL | wx.EXPAND)

        self.RightPanel = wx.Panel(self,-1)
        self.BoxSizer.Add(self.RightPanel,proportion =0, border = 2,flag = wx.ALL | wx.EXPAND)

        self.SetSizer(self.BoxSizer)

        #创建FlexGridSizer
        self.FlexGridSizer=wx.FlexGridSizer( rows=9, cols=1, vgap=5,hgap=5)
        self.FlexGridSizer.SetFlexibleDirection(wx.BOTH)

        #测试按钮1
        self.Button1 = wx.Button(self.RightPanel,-1,"TestButton",size=(100,40),pos=(10,10))
        self.Button1.Bind(wx.EVT_BUTTON,self.Button1Event)

        #测试按钮2
        self.Button2 = wx.Button(self.RightPanel,-1,"AboutButton",size=(100,40),pos=(10,10))
        self.Button2.Bind(wx.EVT_BUTTON,self.Button2Event)

        self.Button3 =wx.Button(self.RightPanel,-1,"FFT",size=(100,40),pos=(10,10))
        self.Button3.Bind(wx.EVT_BUTTON,self.Button3Event)

        #加入Sizer中
        self.FlexGridSizer.Add(self.Button1,proportion =0, border = 5,flag = wx.ALL | wx.EXPAND)
        self.FlexGridSizer.Add(self.Button2,proportion =0, border = 5,flag = wx.ALL | wx.EXPAND)
        self.FlexGridSizer.Add(self.Button3,proportion =0, border = 5,flag = wx.ALL | wx.EXPAND)

        self.RightPanel.SetSizer(self.FlexGridSizer)

        #状态栏
        self.StatusBar()

        self.all_data=[]
        self.line_data=[]
        #MPL2_Frame界面居中显示
        self.Centre(wx.BOTH)



    #按钮事件,用于测试
    def Button1Event(self,event):
        self.MPL1.cla()#必须清理图形,才能显示下一幅图
        x=np.arange(-5,5,0.2)
        y=np.cos(x)
        x1 = np.arange(-5,5,0.2)
        y1 = 10*np.sin(x1)
        self.MPL1.plot(self.MPL1.axes,x,y,'r')
        self.MPL1.plot(self.MPL1.axes1,x1,y1,'--*g')#test!!!!

        self.MPL1.xticker(2.0,1.0)
        self.MPL1.yticker(0.5,0.1)
        self.MPL1.title_MPL("MPL1")
        self.MPL1.ShowHelpString("You Can Show MPL1 Helpful String Here !")
        self.MPL1.grid()
        self.MPL1.UpdatePlot()#必须刷新才能显示

        self.MPL2.cla()
        self.MPL2.plot(self.MPL2.axes,x,np.sin(x),':^b')#test!!!!!
        self.MPL2.xticker(1.0,0.5)
        self.MPL2.yticker(0.2,0.1)
        self.MPL2.title_MPL("MPL2")
        self.MPL2.grid()
        self.MPL2.UpdatePlot()


    def Button2Event(self,event):
        filenamelist=["T_P0_M1_ap_step_0.txt","T_P0_M1_av_step_0.txt","T_P0_M1_cp_step_0.txt","T_P0_M1_fe_step_0.txt",]

        plot_all(filenamelist,self.MPL1.axes,self.MPL1.axes1)
        plot_all(filenamelist,self.MPL2.axes,self.MPL2.axes1)
#        plot_all.callback.fft()
        self.MPL1.UpdatePlot()
        self.MPL2.UpdatePlot()
        self.AboutDialog()


    def Button3Event(self,mode="step"):
        filename_list=["T_P0_M1_ap_step_0.txt","T_P0_M1_av_step_0.txt","T_P0_M1_cp_step_0.txt","T_P0_M1_fe_step_0.txt",]
        data_all={}.fromkeys(('ap','cp','av','cv','ca','aa','fe','None'),0)

        ax1=self.MPL2.axes
        ax2=self.MPL2.axes1
        ax1.clear()
        ax2.clear()
        data_gather_period=200
        #~~~~~~~~将本次运动采集的所有数据都读取进来~~~~~~~~~
        for key in data_all:
            for each_file in filename_list:
                if key in each_file:
                    data_all[key]=get_data_from_file(each_file)
                    break
            #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#

        #~~~~~~~~根据需要绘制的文件名，得到相应的key，用于字典存放数据

        key_list_for_plot=[]
        for each in filename_list:
            key_list_for_plot.append(get_key_from_filename(each))

        line_data=get_data_from_all_key_list_and_filename_list(key_list_for_plot,filename_list,data_all)
        freq1,spectrum_f1,freq2,spectrum_f2,freq3,spectrum_f3,freq4,spectrum_f4=calc_fft(line_data[0],line_data[1],line_data[2],line_data[3],dt=float(data_gather_period),dt_unit='us')

        ax1.clear()
        ax2.clear()

        ax1.set_yscale('log')
        ax2.set_yscale('log')
        ax1.xaxis.grid(True, which='major')
        ax1.xaxis.grid(True, which='minor')

        line1 = ax1.plot(freq1[:len(spectrum_f1)/2],spectrum_f1[:len(spectrum_f1)/2],color = 'b')
        line2 = ax1.plot(freq2[:len(spectrum_f2)/2],spectrum_f2[:len(spectrum_f2)/2],color = 'g')
        line3 = ax2.plot(freq3[:len(spectrum_f3)/2],spectrum_f3[:len(spectrum_f3)/2],color = 'r',)
        line4 = ax2.plot(freq4[:len(spectrum_f4)/2],spectrum_f4[:len(spectrum_f4)/2],color = 'brown')

        #ax1.set_title(motor_name+' motion executed at '+executed_time)
        #ax1.set_ylabel(y2_ylabel,color='g')
        ax1.set_xlabel('freq(Hz)')

        #ax2.set_ylabel(y3_ylabel,color='r')
        ax2.yaxis.tick_right()
        ax2.yaxis.set_label_position('right')
        for tl in ax2.get_yticklabels():
            tl.set_color('r')
        ax1.grid(True)
        #ax1.set_ylim(ymin=-10)

        ax1.legend((line1,line2,line3,line4),("y1_ylabel","y2_ylabel","y3_ylabel","y4_ylabel"),loc='best')#get_freq_amp_of_data_by_fft

        if (mode=='step'):
            cmd_position = max(data_all['cp'])
            raise_time = str(get_raise_time(data_all['ap'],cmd_position))
            setting_time = str(get_setting_time(data_all['ap'][:len(data_all['ap'])/4],cmd_position))
            str_annotate = 'raise time=' + raise_time + x1_unit+"     the setting time="+ setting_time + x1_unit
            ax1.annotate(str_annotate, xy=(0.2, 0),  xycoords='figure fraction',
                xytext=(20, 20), textcoords='offset points',
                ha="left", va="bottom",
            )

        #plt.axis([0,1000,0,max(spectrum_f1)])
        plt.draw()
        self.MPL2.UpdatePlot()



    #自动创建状态栏
    def StatusBar(self):
        self.statusbar = self.CreateStatusBar()
        self.statusbar.SetFieldsCount(3)
        self.statusbar.SetStatusWidths([-2, -2, -1])


    #About对话框
    def AboutDialog(self):
        dlg = wx.MessageDialog(self, '\twxMatPlotLib\t\nMPL_Panel_base,MPL_Panel,MPL_Frame and MPL2_Frame \n Created by Wu Xuping\n Version 1.0.0 \n 2012-02-01',
            'About MPL_Frame and MPL_Panel', wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()





def plot_all(filename_list,ax1,ax2,data_gather_period=0.000402,mode="step",left_axis='Position',right_axis='Fellowing_Error',pid_para='Ixx30=10000',
             data_gather_period_time_unit='us',
             y1_unit='cts',
             y2_unit='cts',
             y3_unit='cts',
             y4_unit='cts',
             x1_unit='ms',
             x1_factor=1,
             x2_factor=1,
             x3_factor=1,
             x4_factor=1):
    """
    用于绘制4个数据文件的图形，根据不能的mode显示不同的提示信息，根据left_axis和right_axis显示不同的legend.
    len(filename_list)为4,文件的格式为纯数据,以空格为分隔符。
    数据采样时间间隔为0.000402s,可以用来进行FFT变换
    模式为对单元就是"unit"，对调试就是"step","ramp","para","trap"
    left_axis为左边Y轴的单位。
    right_axis为右边Y周的单位。
    pid_para为当前的PID参数
    y1_unit,y2_unit,y3_unit,y4_unit为主要的数据的长度单位：cts,mm,度,
    x1_factor,x2_factor,x3_factor,x4_factor为长度的比例因子,可以在以后用来进行坐标单位变换,
    """
    global data1_to_save
    global data2_to_save
    global data3_to_save
    global data4_to_save
    ax1.clear()
    ax2.clear()
    #初始化字典，用于存放不同类型的数据。
    #ap:actual position,cp:command position
    #cv:command velocity,av:actual velocity
    #ca:command acc,aa:actual acc
    #fe:fellowing error
    #None:无数据
    data_all={}.fromkeys(('ap','cp','av','cv','ca','aa','fe','None'),0)
    #~~~~~~~~将本次运动采集的所有数据都读取进来~~~~~~~~~
    for key in data_all:
        for each_file in filename_list:
            if key in each_file:
                data_all[key]=get_data_from_file(each_file)
                break
        #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#

    #~~~~~~~~根据需要绘制的文件名，得到相应的key，用于字典存放数据

    key_list_for_plot=[]
    for each in filename_list:
        key_list_for_plot.append(get_key_from_filename(each))

    line_data=get_data_from_all_key_list_and_filename_list(key_list_for_plot,filename_list,data_all)
    print "in plot_all"
    class Index:
        ind = 0
        def fft(self, event):
            self.ind += 1
            freq1,spectrum_f1,freq2,spectrum_f2,freq3,spectrum_f3,freq4,spectrum_f4=calc_fft(line_data[0],line_data[1],line_data[2],line_data[3],dt=float(data_gather_period),dt_unit='us')

            ax1.clear()
            ax2.clear()

            ax1.set_yscale('log')
            ax2.set_yscale('log')
            ax1.xaxis.grid(True, which='major')
            ax1.xaxis.grid(True, which='minor')

            line1 = ax1.plot(freq1[:len(spectrum_f1)/2],spectrum_f1[:len(spectrum_f1)/2],color = 'b')
            line2 = ax1.plot(freq2[:len(spectrum_f2)/2],spectrum_f2[:len(spectrum_f2)/2],color = 'g')
            line3 = ax2.plot(freq3[:len(spectrum_f3)/2],spectrum_f3[:len(spectrum_f3)/2],color = 'r',)
            line4 = ax2.plot(freq4[:len(spectrum_f4)/2],spectrum_f4[:len(spectrum_f4)/2],color = 'brown')

            ax1.set_title(motor_name+' motion executed at '+executed_time)
            ax1.set_ylabel(y2_ylabel,color='g')
            ax1.set_xlabel('freq(Hz)')

            ax2.set_ylabel(y3_ylabel,color='r')
            ax2.yaxis.tick_right()
            ax2.yaxis.set_label_position('right')
            for tl in ax2.get_yticklabels():
                tl.set_color('r')
            ax1.grid(True)
            #ax1.set_ylim(ymin=-10)

            ax1.legend((line1,line2,line3,line4),(y1_ylabel,y2_ylabel,y3_ylabel,y4_ylabel),loc='best')#get_freq_amp_of_data_by_fft

            if (mode=='step'):
                cmd_position = max(data_all['cp'])
                raise_time = str(get_raise_time(data_all['ap'],cmd_position))
                setting_time = str(get_setting_time(data_all['ap'][:len(data_all['ap'])/4],cmd_position))
                str_annotate = 'raise time=' + raise_time + x1_unit+"     the setting time="+ setting_time + x1_unit
                ax1.annotate(str_annotate, xy=(0.2, 0),  xycoords='figure fraction',
                    xytext=(20, 20), textcoords='offset points',
                    ha="left", va="bottom",
                )

            #plt.axis([0,1000,0,max(spectrum_f1)])
            plt.draw()

        def normal(self, event):
            self.ind -= 1
            ax1.clear()
            ax2.clear()
            line1 = ax1.plot(np.multiply(x1_factor,np.arange(0,len(line_data[0]))),line_data[0], color = 'b')
            line2 = ax1.plot(np.multiply(x1_factor,np.arange(0,len(line_data[1]))),line_data[1], color = 'g')
            line3 = ax2.plot(np.multiply(x1_factor,np.arange(0,len(line_data[2]))),line_data[2], color = 'r')
            line4 = ax2.plot(np.multiply(x1_factor,np.arange(0,len(line_data[3]))),line_data[3], color = 'brown')
            ax1.set_title(motor_name+' motion executed at '+executed_time)
            ax1.set_ylabel(y2_ylabel,color='g')
            ax1.set_xlabel('time(ms)')
            ax2.set_ylabel(y3_ylabel,color='r')
            #plt.axis([0,len(y1),y1.min(),y1.max()])

            ax2.yaxis.tick_right()
            ax2.yaxis.set_label_position('right')
            for each in [line_data[2],line_data[3]]:
                if len(line_data[2]):
                    for tl in ax2.get_yticklabels():
                        tl.set_color('r')
                if len(line_data[3]):
                    for tl in ax2.get_yticklabels():
                        tl.set_color('brown')

            ax1.legend((line1,line2,line3,line4),(y1_ylabel,y2_ylabel,y3_ylabel,y4_ylabel))

            if (mode=='step'):
                cmd_position = max(data_all['cp'])
                raise_time = str(get_raise_time(data_all['ap'],cmd_position))
                setting_time = str(get_setting_time(data_all['ap'][:len(data_all['ap'])/4],cmd_position))
                str_annotate = 'raise time=' + raise_time + x1_unit+"     the setting time="+ setting_time + x1_unit
                ax1.annotate(str_annotate, xy=(0.2, 0),  xycoords='figure fraction',
                    xytext=(20, 20), textcoords='offset points',
                    ha="left", va="bottom",
                )
            ax1.grid(True)
            plt.draw()

    y1_ylabel = get_ylabel(filename[0],y1_unit)
    y2_ylabel = get_ylabel(filename[1],y2_unit)
    y3_ylabel = get_ylabel(filename[2],y3_unit)
    y4_ylabel = get_ylabel(filename[3],y4_unit)

    #get line1以及起相关属性
    # #!!!!!!!!!!!!!时间计算有问题,有时候除以1000会出错＝。＝！
    #!!!!!!!!!!!data_gather_period=300/174.*1000#应该算是经验值，感觉是这多ms一个采样点。。。。。待查。。。
    if data_gather_period_time_unit =='us' and x1_unit=='ms':

        x1_factor = float(data_gather_period)/1000.
        print "x1_factor is:",x1_factor

    x1 = numpy.arange(0,len(line_data[0])*x1_factor,x1_factor)#get the real xvalue after multiply a factors
    print "len(x1),len(line_data[0]) is:",len(x1),len(line_data[0])


    line1=ax1.plot(x1,line_data[0],'b')
    ax1.set_xlabel('time(ms)')
    # Make the y-axis label and tick labels match the line color.
    ax1.set_ylabel(y1_ylabel,color='b')
    for tl in ax1.get_yticklabels():
        tl.set_color('b')

    #get x2
    if data_gather_period_time_unit =='us' and x1_unit=='ms':
        x2_factor = float(data_gather_period)/1000.

    x2 = numpy.arange(0,len(line_data[1])*x2_factor,x2_factor)#get the real xvalue after multiply a factors

    line2=ax1.plot(x2, line_data[1], 'g')
    ax1.set_xlabel('time(ms)')
    ax1.set_ylabel(y2_ylabel,color='g')




    #ax2 = ax1.twinx()!!!!!!!!!!!!!!!!!!!

    #get x3
    if data_gather_period_time_unit =='us' and x1_unit=='ms':
        x3_factor = float(data_gather_period)/1000.
    x3 = numpy.arange(0,len(line_data[2])*x3_factor,x3_factor)#get the real xvalue after multiply a factors
    line3=ax2.plot(x3, line_data[2], 'r')
    ax2.set_ylabel(y3_ylabel,color='r')
    for tl in ax2.get_yticklabels():
        tl.set_color('r')
        #get x4
    if data_gather_period_time_unit =='us' and x1_unit=='ms':
        x4_factor = float(data_gather_period)/1000.
    x4 = numpy.arange(0,len(line_data[3])*x4_factor,x4_factor)#get the real xvalue after multiply a factors
    line4 = ax2.plot(x4,line_data[3],'brown')
    for tl in ax2.get_yticklabels():
        tl.set_color('brown')

    callback = Index()
    axprev = plt.axes([0.7, 0.025, 0.1, 0.035])
    axnext = plt.axes([0.81, 0.025, 0.1, 0.035])

    bnext = Button(axnext, 'FFT')
    bnext.on_clicked(callback.fft)
    bprev = Button(axprev, 'normal')
    bprev.on_clicked(callback.normal)

    if mode == "step":
        raise_time = str(get_raise_time(line_data[1],cmd_position=200))
        setting_time = str(get_setting_time(line_data[1][:len(line_data[1])/4],cmd_position=200))
        str_annotate = 'raise time=' + raise_time + x1_unit+"     the setting time="+ setting_time + x1_unit

        ax1.annotate(str_annotate, xy=(0.2, 0),  xycoords='figure fraction',
            xytext=(20, 20), textcoords='offset points',
            ha="left", va="bottom",
        )
    for each in filename_list:
        if each !="None":
            executed_time = time.strftime('%a, %d %b %Y %H:%M:%S ',time.gmtime(getctime(each)))
            break
        else:
            executed_time = "Unkown"

    motor_name = filename[1][:-12]
    ax1.set_title(motor_name+' motion executed at '+executed_time)


    ax1.legend((line1,line2,line3,line4),(y1_ylabel,y2_ylabel,y3_ylabel,y4_ylabel))
    data1_to_save = line_data[0]
    data2_to_save = line_data[1]
    data3_to_save = line_data[2]
    data4_to_save = line_data[3]
    #  resetax1 = axes([0.7, 0.01, 0.05, 0.075])
    #  button1 = Button(resetax1, 'Save_y1')
    #  button1.on_clicked(savedata1)
    #  resetax2 = axes([0.85, 0.01, 0.05, 0.075])
    #  button2 = Button(resetax2, 'Save_y2')
    #  button2.on_clicked(savedata2)
    ax1.grid(True)
    plt.draw()

########################################################################

#主程序测试
if __name__ == '__main__':
    app = wx.PySimpleApp()
    frame = MPL_Frame()
    #frame =MPL2_Frame()
    frame.Center()
    frame.Show()
    app.MainLoop()
